import baseurl from '../common/common.js'
class Request {
	constructor() {
		this.BASE_URL = baseurl
	}
	getBaseUrl() {
		return this.BASE_URL
	}
	post(url, data = {}) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.BASE_URL + url,
				data: data,
				header: {
					'content-type': 'application/json',
					'Authorization': 'Bearer ' + uni.getStorageSync('token') || ''
				},
				method: 'POST',
				success: res => {
					if(res.data.code == 401) {
						resolve(res.data)
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						uni.clearStorage()
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}else {
						resolve(res.data)
					}
				},
				fail: err => {
					reject(err)
				}
			})
		})
	}
	get(url, data = {}) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.BASE_URL + url,
				data: data,
				header: {
					'content-type': 'application/json',
					'Authorization': 'Bearer ' + uni.getStorageSync('token') || ''
				},
				method: 'GET',
				success: res => {
					if(res.data.code == 401) {
						resolve(res.data)
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						uni.clearStorage()
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}else {
						resolve(res.data)
					}
				},
				fail: err => {
					reject(err)
				}
			})
		})
	}
	uploadFile(url, path) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: this.BASE_URL + url,
				filePath: path,
				name: 'file',
				method: 'POST',
				fileType: 'image',
				header: {
					token: uni.getStorageSync('token') || ''
				},
				success: uploadFileRes => {
					let upData = JSON.parse(uploadFileRes.data);
					resolve(upData)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	}
}
const http = new Request()
export default http